package com.trt.beibei.core;

import com.trt.beibei.model.User;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tanrentao
 * @date 2021-08-13
 * @desc
 */
public class LocalUser {

    // ThreadLocal 线程， Map 一组数据 不应该思考多个用户
    // ThreadLocal 解决复杂线程方面的问题，线程的复杂性封装好了，只需要ThreadLocal就能保证在多线程的环境存储数据
    // 很多情况下采用锁解决线程安全，ThreadLocal可以解决，没必要用锁


//        private static User user; // 静态变量涉及到多线程读写情况下，线程安全问题，改成Map也不能回避线程安全问题，HashMap不是线程安全
//
//        public static void set(User user, Integer scope) {
//            LocalUser.user = user;
//        }
//
//        public static User getUser() {
//            return LocalUser.user;
//        }

    // ThreadLocal 解决线程安全
    private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public static void set(User user, Integer scope) {
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("scope", scope);
        LocalUser.threadLocal.set(map);
    }

    public static User getUser() {
        Map<String, Object> map = LocalUser.threadLocal.get();
        User user = (User)map.get("user");
        return user;
    }

    public static Integer getScope() {
        Map<String, Object> map = LocalUser.threadLocal.get();
        Integer scope = (Integer)map.get("scope");
        return scope;
    }

    public static void clear() {
        LocalUser.threadLocal.remove();
    }


}
